using System;
using System.IO;

namespace Slaks.Readers
{
	
	public abstract class FileReader : Slaks.Readers.AReader, IDisposable
	{
    protected StreamReader m_stream = null;
		protected string m_filename = null;
		protected System.Text.Encoding m_encoding;

		public FileReader(System.Text.Encoding encoding)
		{
			m_encoding = encoding;
		}

		public FileReader(string filename, System.Text.Encoding encoding)
		{
			m_filename = filename;
			m_encoding = encoding;
		}

    public FileReader(Slaks.Filters.AFilter filter,string filename, System.Text.Encoding encoding) : base(filter)
    {
			m_encoding = encoding;
			m_filename = filename;
    }

		public string FileName
		{
			get { return m_filename;}
			set { m_filename = value; }
		}

		/// <summary>
		/// Stream must be openned before using FileReader
		/// </summary>
		public override void OpenStream()
		{
			if (m_filename == null) throw new Exception("Must provide name of the file");
			if (!File.Exists(m_filename)) throw new FileNotFoundException("The provided file name does not exists",m_filename);
			try
			{
				m_stream = new StreamReader(m_filename,m_encoding,true);
			}
			catch(Exception)
			{
				this.CloseReader();
				throw;
			}
		}

    /// <summary>
    /// Close the reader stream
    /// </summary>
    public override void CloseReader()
    {
      if (m_stream != null) m_stream.Close();
    }

    public override bool Eof()
    {
      return m_stream.Peek() < 0 && m_innerBuffer == char.MinValue; 
    }


    #region IDisposable Members
    public void Dispose()
    {
      if (m_stream != null) m_stream.Close();
    }
    #endregion
	}
}
